<?php
namespace Admin\Controller;

class MailerController extends AbstractController  {
	
	protected $Mail;
	protected $results = array();
	
	public function _initialize(){
		//$this->Form = D('Sysconfig');
		Vendor('PHPMailer.PHPMailerAutoload');     
    	$this->Mail = new \PHPMailer(); //实例化
    }
    
    public function index(){
    	$this->display();
    }
    
    public function emailSend(){    	
    	$in = I();
    	$res = D('Sysconfig')->field("ConfigName,ConfigValue")->where(array("ConfigClass"=>"smtp"))->select();
    	foreach($res AS $k => $v){
			$newres[$v['ConfigName']] = $v['ConfigValue'];
		}
    	$newres['body'] = $in['body'];
    	$newres['email'] = $in['email'];
		switch($newres['server']){
			case 'smtp.qq.com':
				$this->Send($newres);
			break;
			case 2:
			break;
			case 3:
			break;
			default:
				 //$this->error('请传入发送类型！');
			break;
		}
	}

	public function Send($Sendata){
		if(empty($Sendata['body']) && empty($Sendata['email'])) $this->error('邮箱或内容，不能为空！');
		$body = $Sendata['body']; #内容
		$this->Mail->IsSMTP();
	 	$this->Mail->SMTPAuth = true; 
	 	$this->Mail->SMTPKeepAlive = true; 
	  	$this->Mail->SMTPSecure = "ssl"; 
	  	$this->Mail->CharSet = "utf-8";
	   	$this->Mail->Host = $Sendata['server']; 
	    $this->Mail->Port = 465;
	 	$this->Mail->Username = $Sendata['username']; 
	  	$this->Mail->Password = $Sendata['password'];
	    $this->Mail->From = $Sendata['username']; //发件人邮箱
	    $this->Mail->FromName = "发件人"; //发件人名称
	    $this->Mail->Subject = "主题"; //主题名称
	    $this->Mail->AltBody = $body;
	    $this->Mail->WordWrap = 50; // set word wrap 
	    $this->Mail->MsgHTML($body);    
		$this->Mail->AddReplyTo($Sendata['username'],"");  #设置回复地址  回复人名称
		//添加附件，此处附件与脚本位于相同目录下否则填写完整路径 
		#$this->Mail->AddAttachment("attachment.jpg"); 
	 	#$this->Mail->AddAttachment("attachment.zip"); 
	 	//设置邮件接收方的邮箱和姓名 
	    $this->Mail->AddAddress($Sendata['email'],""); 
	    //使用HTML格式发送邮件 
		$this->Mail->IsHTML(true); 
		//通过Send方法发送邮件根据发送结果做相应处理 
		$res = $this->Mail->Send();
		if($res == true){
			//$this->success('邮件发送成功');
			$this->results['state'] = 1;
			$this->results['msg'] = "邮件发送成功！";
		}else{
			$this->results['state'] = 0;
			$this->results['msg'] = "删邮件发送失败！";
		}
		echo json_encode($this->results);
	}
	
	
}